package com.manage.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.manage.dao.*;
import com.manage.pojo.dto.CaseFindDTO;
import com.manage.pojo.entity.*;
import com.manage.pojo.entity.case_manage.*;
import com.manage.pojo.vo.CaseManageListVO;
import com.manage.pojo.vo.CmCaseWarningVO;
import com.manage.pojo.vo.CmSysUserVO;
import com.manage.pojo.vo.DepositSettlementStatusVO;
import com.manage.service.ICmCaseManageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class CmCaseManageServiceImpl implements ICmCaseManageService {

    @Autowired
    private CmCaseManageMapper cmCaseManageMapper;

    @Autowired
    private CmCaseMapper cmCaseMapper;

    @Autowired
    private CmCaseBatchMapper cmCaseBatchMapper;

    @Autowired
    private CmCaseAssignMapper cmCaseAssignMapper;

    @Autowired
    private CmTaskAssignMapper cmTaskAssignMapper;

    @Autowired
    private CmSysUserMapper cmSysUserMapper;

    @Autowired
    private CmLoansTypeMapper cmLoansTypeMapper;

    @Autowired
    private CmSysRoleMapper cmSysRoleMapper;

    @Autowired
    private CmSysUserRoleMapper cmSysUserRoleMapper;

    // 查询案件列表
    public CaseManageDataInfo selectCmCaseManage(CaseManageParam caseManageParam) {
        // 设置分页参数默认值
        if (caseManageParam.getPageNum() == null || caseManageParam.getPageNum() <= 0) {
            caseManageParam.setPageNum(1);
        }
        if (caseManageParam.getPageSize() == null || caseManageParam.getPageSize() <= 0) {
            caseManageParam.setPageSize(10);
        }
        caseManageParam.setOffset((caseManageParam.getPageNum() - 1) * caseManageParam.getPageSize());

        // 头部 导航栏数据
        CaseManageDataInfo caseManageDataInfo = cmCaseManageMapper.selectCmCaseManageData(caseManageParam);
        // 列表数据
        caseManageDataInfo.setCaseManageDataList(cmCaseManageMapper.selectCmCaseManageDataList(caseManageParam));
        // 银行列表
        caseManageDataInfo.setBankList(cmCaseManageMapper.selectBankList(caseManageParam));
        // 支行列表
        caseManageDataInfo.setBranchList(cmCaseManageMapper.selectBankBranchList(caseManageParam));
        // 律师列表
        caseManageDataInfo.setGranteeLawyerList(cmCaseManageMapper.selectGranteeLawyerList(caseManageParam));
        caseManageDataInfo.setSponsorLawyerList(cmCaseManageMapper.selectSponsorLawyerList(caseManageParam));
        caseManageDataInfo.setPrincipalLawyerList(cmCaseManageMapper.selectPrincipalLawyerList(caseManageParam));
        // 已结律师费金额
        caseManageDataInfo.setClosedCaseLawyerFeeAmount(cmCaseManageMapper.sumClosedCaseLawyerFeeAmount());
        return caseManageDataInfo;
    }

    // 案件结算
    public CaseResultDto caseResult(CaseResultParam caseResultParam) {
        return cmCaseManageMapper.caseResult(caseResultParam);
    }

    // 分配案件
    public CaseAssignDto caseAssign(CaseAssignParam caseAssignParam){
        CaseAssignDto caseAssignDto=new CaseAssignDto();
        // 分配案件接收人员 --主办律师
        caseAssignDto.setAssign(cmCaseManageMapper.selectAssignList());
        // 分配案件列表
        caseAssignDto.setCaseAssignList(cmCaseManageMapper.caseAssignList(caseAssignParam));
        return caseAssignDto;
    }

    //  移交案件
    public CaseTransferDto caseTransfer(CaseTransferParam caseTransferParam){
        CaseTransferDto caseTransferDto=new CaseTransferDto();
        //  移交案件接收人员 --主办律师
        caseTransferDto.setTransferList(cmCaseManageMapper.selectAssignList());
        //  移交案件列表
        caseTransferDto.setCaseTransferList(cmCaseManageMapper.caseTransferList(caseTransferParam));
        return caseTransferDto;
    }

    //  委托记录
    public CaseEntrustedRecordDto caseEntrustedRecord(CaseEntrustedRecordParam caseEntrustedRecordParam){
        CaseEntrustedRecordDto caseEntrustedRecordDto=cmCaseManageMapper.caseEntrustedRecord(caseEntrustedRecordParam);

        // 获取文件实体类
        caseEntrustedRecordDto.setTaskAgentBook(cmCaseManageMapper.selectFileAttachment(caseEntrustedRecordDto.getTaskAgentBookId()));
        caseEntrustedRecordDto.setTaskDetails(cmCaseManageMapper.selectFileAttachment(caseEntrustedRecordDto.getTaskDetailsId()));

        return caseEntrustedRecordDto;
    }

    // 查询委托对应的所有案件
    public List<CmCase> caseEntrustedList(CaseEntrustedParam caseEntrustedParam){
        return cmCaseManageMapper.caseEntrustedList(caseEntrustedParam);
    }

    public Integer caseAssignConfirm(CaseAssignConfirmParam caseAssignConfirmParam){
        return cmCaseManageMapper.caseAssignConfirm(caseAssignConfirmParam);
    }

    public Integer caseTransferConfirm(CaseTransferConfirmParam caseTransferConfirmParam){
        return cmCaseManageMapper.caseTransferConfirm(caseTransferConfirmParam);
    }

    @Override
    public CaseManageListVO caseManageList(CaseFindDTO caseFindDTO) {
        System.out.println(caseFindDTO);
        LambdaQueryWrapper<CmCase> queryWrapper = new LambdaQueryWrapper<>();

        queryWrapper.eq(caseFindDTO.getLoanNo()!=null,CmCase::getLoanNo, caseFindDTO.getLoanNo());


        queryWrapper.eq(caseFindDTO.getDebtorName()!=null,CmCase::getDebtorName, caseFindDTO.getDebtorName());


        queryWrapper.eq(caseFindDTO.getCaseBatchId()!=null, CmCase::getCaseBatchId, caseFindDTO.getCaseBatchId());


        queryWrapper.eq(caseFindDTO.getWarningStatus() != null, CmCase::getWarningStatus, caseFindDTO.getWarningStatus());


        queryWrapper.eq(caseFindDTO.getDepositSettlementStatus()!=null ,CmCase::getDepositSettlementStatus, caseFindDTO.getDepositSettlementStatus());


        queryWrapper.between(caseFindDTO.getBeginNodeDeadline()!=null && caseFindDTO.getEndNodeDeadline()!=null,CmCase::getNodeDeadline, caseFindDTO.getBeginNodeDeadline(), caseFindDTO.getEndNodeDeadline());


        queryWrapper.between(caseFindDTO.getBeginEntrustDate()!=null && caseFindDTO.getEndEntrustDate()!=null,CmCase::getEntrustDate, caseFindDTO.getBeginEntrustDate(), caseFindDTO.getEndEntrustDate());


        queryWrapper.between(caseFindDTO.getBeginDepositPaymentDate()!=null && caseFindDTO.getEndDepositPaymentDate()!=null, CmCase::getDepositPaymentDate, caseFindDTO.getBeginDepositPaymentDate(), caseFindDTO.getEndDepositPaymentDate());


        queryWrapper.eq(caseFindDTO.getGranteeId()!=null,CmCase::getGranteeId, caseFindDTO.getGranteeId());

        queryWrapper.eq(caseFindDTO.getCaseStage() !=null ,CmCase::getCaseStage, caseFindDTO.getCaseStage()+"阶段");

        IPage<CmCase> page = new Page<>(caseFindDTO.getPageNum(),caseFindDTO.getPageSize());
        List<CmCase> cmCases = cmCaseMapper.selectList(page,queryWrapper);
        IPage<CmCase> resultPage = cmCaseMapper.selectPage(page, queryWrapper);
        Long total = resultPage.getTotal();
        Long pages = resultPage.getPages();
        System.out.println("总数量：" + total);
        System.out.println("总页数：" + pages);
        List<CaseManage> caseManageList = new ArrayList<>();
        for(CmCase cmCase:cmCases){
            LambdaQueryWrapper<CmCaseBatch> queryWrapperBatch = new LambdaQueryWrapper<>();
            LambdaQueryWrapper<CmCaseAssign> queryWrapperAssign = new LambdaQueryWrapper<>();
            LambdaQueryWrapper<CmSysUser> queryWrapperGranteeUser = new LambdaQueryWrapper<>();
            LambdaQueryWrapper<CmSysUser> queryWrapperPrincipalUser = new LambdaQueryWrapper<>();
            LambdaQueryWrapper<CmSysUser> queryWrapperSponsorUser = new LambdaQueryWrapper<>();
            LambdaQueryWrapper<CmSysUser> queryWrapperHandler = new LambdaQueryWrapper<>();
            LambdaQueryWrapper<CmTaskAssign> queryWrapperTask = new LambdaQueryWrapper<>();
            LambdaQueryWrapper<CmLoansType> queryWrapperLoansType = new LambdaQueryWrapper<>();

            //查找该案件批次
            queryWrapperBatch.eq(cmCase.getCaseBatchId()!=null, CmCaseBatch::getId,cmCase.getCaseBatchId());
            CmCaseBatch cmCaseBatch = cmCaseBatchMapper.selectOne(queryWrapperBatch);
            System.out.println(cmCaseBatch);
            if(cmCaseBatch==null)
                cmCaseBatch = new CmCaseBatch();

            //查找案件分配情况
            queryWrapperAssign.eq(cmCase.getId() !=null , CmCaseAssign::getCaseId,cmCase.getId());
            CmCaseAssign cmCaseAssign = cmCaseAssignMapper.selectOne(queryWrapperAssign);
            System.out.println(cmCaseAssign);
            if(cmCaseAssign==null)
                cmCaseAssign = new CmCaseAssign();

            //查找承接律师
            CmSysUser cmSysGranteeUser = null;
//            queryWrapperGranteeUser.eq(cmCase.getGranteeId()!=null,CmSysUser::getId,cmCase.getGranteeId());
            if(cmCase.getGranteeId()!=null){
             cmSysGranteeUser = cmSysUserMapper.selectById(cmCase.getGranteeId());
            }
            if(cmSysGranteeUser==null){
                cmSysGranteeUser = new CmSysUser();
            }

            //查找负责律师
            CmSysUser cmSysPrincipalUser = null;
            CmSysUser cmSysSponsorUser = null;
            if(cmCaseAssign.getPrincipalId() != null) {
                queryWrapperPrincipalUser.eq(CmSysUser::getId, cmCaseAssign.getPrincipalId());
                cmSysPrincipalUser = cmSysUserMapper.selectOne(queryWrapperPrincipalUser);

            }
            cmSysPrincipalUser = cmSysPrincipalUser == null ? new CmSysUser() : cmSysPrincipalUser;
            //查找主办律师
            if(cmCaseAssign.getPrincipalId() != null) {
                queryWrapperSponsorUser.eq(CmSysUser::getId, cmCaseAssign.getSponsorId());
                cmSysSponsorUser = cmSysUserMapper.selectOne(queryWrapperSponsorUser);
                ;
            }
            cmSysSponsorUser = cmSysSponsorUser == null ? new CmSysUser() : cmSysSponsorUser;

            //查找经办人
            queryWrapperTask.eq(cmCase.getId()!=null,CmTaskAssign::getCaseId,cmCase.getId());
            CmTaskAssign cmTaskAssign = cmTaskAssignMapper.selectOne(queryWrapperTask);

            CmSysUser cmSysHandler = new CmSysUser();
            if(cmTaskAssign!=null) {
                queryWrapperHandler.eq(cmTaskAssign.getHandlerId() != null, CmSysUser::getId, cmTaskAssign.getHandlerId());
                cmSysHandler = cmSysUserMapper.selectOne(queryWrapperHandler);
            }
            cmSysHandler = cmSysHandler==null?new CmSysUser():cmSysHandler;

            //查找贷款种类
            queryWrapperLoansType.eq(cmCase.getLoanTypeId()!=null,CmLoansType::getId,cmCase.getLoanTypeId());
            CmLoansType cmLoansType = cmLoansTypeMapper.selectOne(queryWrapperLoansType);
            cmLoansType = cmLoansType==null?new CmLoansType():cmLoansType;

            caseManageList.add(new CaseManage(cmCase.getId(),cmCase.getPublicId(),cmCaseBatch.getBatchName(),cmCase.getEntrustDate(),
                                                cmCase.getDebtorName(),cmLoansType.getPublicId(),
                                                cmCase.getPrincipalAmount(),cmCase.getLoanDueDate(),
                                                cmCase.getContractName(),cmCase.getCaseStage(),
                                                cmCase.getCaseNode(),cmCase.getNodeDeadline(),cmCase.getLatestDocument(),
                                                cmCase.getWarningStatus(),cmCase.getLimitationPeriod(),
                                                cmCase.getLoanNo(),cmCase.getBasicAttorneyFee2(),cmCase.getRiskAttorneyFee(),
                                                cmCase.getDepositAmount(),cmCase.getDepositRefundAmount(),
                                                cmCase.getDepositSettlementStatus(),
                                                cmCase.getPenaltyAmount(),cmSysGranteeUser.getName(),
                                                cmSysSponsorUser.getName(),cmSysPrincipalUser.getName(),
                                                cmSysHandler.getName()));
        }
        System.out.println("cmCases:" + cmCases);
        List<CmCaseBatch> cmCaseBatches = cmCaseBatchMapper.selectList(null);


        CaseManageListVO caseManageListVO = new CaseManageListVO(caseManageList,cmCaseBatches,null,null,
               pages,total);
        return caseManageListVO;
    }

    @Override
    public List<CmSysUserVO> caseManageLawyerList(String type) {
        List<CmSysUserVO> cmSysUserVOS = selectLawyerList(type);
        return cmSysUserVOS;
    }

    @Override
    public List<DepositSettlementStatusVO> caseManageDepositSettlementStatusList() {
        //保证金结算状态列表
        List<DepositSettlementStatusVO> depositSettlementStatus = new ArrayList<>();


        /**
         * 保证金结算状态：0在办不可结算,1在办可结算未报，2在办可结算已报，3已办结已结算
         */
        depositSettlementStatus.add(new DepositSettlementStatusVO(0L,"在办不可结算"));
        depositSettlementStatus.add(new DepositSettlementStatusVO(1L,"在办可结算未报"));
        depositSettlementStatus.add(new DepositSettlementStatusVO(2L,"在办可结算已报"));
        depositSettlementStatus.add(new DepositSettlementStatusVO(3L,"已办结已结算"));
        return depositSettlementStatus;
    }

    @Override
    public List<CmCaseWarningVO> caseManageWarningList() {
        List<CmCaseWarningVO> warningStatus = new ArrayList<>();
        /**
         * 预警状态：0正常，1临期，2超期
         */
        warningStatus.add(new CmCaseWarningVO(0L,"正常"));
        warningStatus.add(new CmCaseWarningVO(1L,"临期"));
        warningStatus.add(new CmCaseWarningVO(2L,"超期"));
        return warningStatus;
    }

    @Override
    public List<Map<String,Long>> caseManageStageCount() {
        //获取案件各阶段数量
        Long caseEntrustCount = countOfCaseStage("委托阶段");
        Long caseSuitCount = countOfCaseStage("诉前阶段");
        Long caseLitigationCount = countOfCaseStage("诉讼阶段");
        Long caseJudgmentCount = countOfCaseStage("已判未执行阶段");
        Long caseJudgmentExecutionCount = countOfCaseStage("执行阶段");
        List<Map<String,Long>> stageCount = new ArrayList<>();
        stageCount.add(new HashMap<String,Long>(){{put("委托阶段",caseEntrustCount);}});
        stageCount.add(new HashMap<String,Long>(){{put("诉前阶段",caseSuitCount);}});
        stageCount.add(new HashMap<String,Long>(){{put("诉讼阶段",caseLitigationCount);}});
        stageCount.add(new HashMap<String,Long>(){{put("已判未执行阶段",caseJudgmentCount);}});
        stageCount.add(new HashMap<String,Long>(){{put("执行阶段",caseJudgmentExecutionCount);}});
        return stageCount;
    }


    /**
     * 获取律师列表
     */
    private List<CmSysUserVO> selectLawyerList(String roleName){
        LambdaQueryWrapper<CmSysRole> queryWrapperRole = new LambdaQueryWrapper<>();
        queryWrapperRole.eq(CmSysRole::getRoleName,roleName);
        CmSysRole cmSysRole2 = cmSysRoleMapper.selectOne(queryWrapperRole);
        LambdaQueryWrapper<CmSysUserRole> queryWrapperUserRole = new LambdaQueryWrapper<>();
        if(cmSysRole2 != null) {
            queryWrapperUserRole.eq(CmSysUserRole::getRoleId, cmSysRole2.getId());
            List<CmSysUserRole> cmSysUserRoleList = cmSysUserRoleMapper.selectList(queryWrapperUserRole);

            List<CmSysUserVO> lawyerName = new ArrayList<>();
            for (CmSysUserRole cmSysUserRole : cmSysUserRoleList) {
                LambdaQueryWrapper<CmSysUser> queryWrapperUser = new LambdaQueryWrapper<>();
                queryWrapperUser.eq(CmSysUser::getId, cmSysUserRole.getUserId());
                CmSysUser cmSysUser = cmSysUserMapper.selectOne(queryWrapperUser);
                CmSysUserVO map = new CmSysUserVO();
                map.setId(cmSysUser.getId());
                map.setName(cmSysUser.getName());
                lawyerName.add(map);
            }return lawyerName;
        }
        return null;

    }

    private Long countOfCaseStage(String caseStage){
        LambdaQueryWrapper<CmCase> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CmCase::getCaseStage,caseStage);
        List<CmCase> cmCases = cmCaseMapper.selectList(queryWrapper);
        Long count = Long.valueOf(cmCases.size());
        return count;
    }
}
